/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.openbookformat.obffinder.filters;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.text.BadLocationException;
import org.openbookformat.obffinder.FindResult;
import org.openbookformat.tags.PagebreakTag;
import org.openide.cookies.EditorCookie;
import org.openide.loaders.DataObject;
import org.openide.util.Exceptions;
import org.openide.util.lookup.ServiceProvider;

/**
 *
 * @author matamh0a
 */
@ServiceProvider(service=Filter.class)
public class ContinousPageNumberFilter extends FindReplaceFilter {
    
    public ContinousPageNumberFilter() {
        name = "Continuous Page Numbers Filter";
        findText = "<custom_code>";
        replaceText = "<custom_code>";
        regExp = true;
        ignoreCase = false;
        useVariables = false;
        useIgonreNewLine = true;
        applyToAll = true;
        description = "FIll missing <pagebreak> tags."
                + " footnotes with marks.";
        chapters = new ArrayList<DataObject>();
    }
    
    @Override
    public Map<DataObject, ArrayList<FindResult>> find() {
        Map<DataObject, ArrayList<FindResult>> findResult
                = new HashMap<DataObject, ArrayList<FindResult>>();
        try {
            int startPage = 1;
            String pagebreakRegexp = PagebreakTag.TAG_PATTERN;
            String text = null;
            int firstPage = -1; //first page in this chapter
            int start = -1;  //last page start
            int end = -1;    //last page end
            int prevPage = -1;
            int curPage = -1;
            String tStr = null;
            Pattern pattern = null, inPattern = null;
            Matcher matcher = null, inMatcher = null;
            ArrayList<FindResult> r = null;
            EditorCookie ed = null;
            
            for (int k = 0; k < chapters.size(); k++) {                
                ed = chapters.get(k).getCookie(EditorCookie.class);
                text = ed.openDocument().getText(0, ed.openDocument().getLength());
                
                firstPage = -1;
                r = new ArrayList<FindResult>();

                pattern = Pattern.compile(pagebreakRegexp);
                matcher = pattern.matcher(text);
            
                if (matcher.find()) {
                    //find first page
                    firstPage = Integer.parseInt(pattern.matcher(
                            matcher.group()).replaceFirst("$1"));

                    //fill in missing pages from the start of the page
                    if(firstPage > startPage) {
                        inPattern = Pattern.compile("<book-part\\sindex='\\d+'>");
                        inMatcher = inPattern.matcher(text.substring(0, 150));
                        inMatcher.find();
                        tStr = inMatcher.group();
                        for(int i = startPage; i < firstPage; i++)
                            tStr += "\n" + (new PagebreakTag(i)).toString();
                        r.add(new FindResult(ed, inMatcher.start(), true, inMatcher.group(), tStr));
                    }
                    prevPage = firstPage;
                    start = matcher.start();
                    end = matcher.end();

                    //Find missing pages in the middle of the pages
                    while(matcher.find()) {
                        curPage = Integer.parseInt(pattern.matcher(
                            matcher.group()).replaceFirst("$1"));

                        if(curPage - prevPage > 1) {
                            tStr = (new PagebreakTag(prevPage)).toString();
                            for(int i = prevPage + 1; i < curPage; i++)
                                tStr += "\n" + (new PagebreakTag(i)).toString();
                            r.add(new FindResult(ed, start, true, 
                                    (new PagebreakTag(prevPage)).toString(), tStr));
                        }

                        prevPage = curPage;
                        start = matcher.start();
                        end = matcher.end();
                    }
                    
                    int x1 = end;
                    int x2 = text.lastIndexOf("<");
                    System.out.println(end);
                    System.out.println(text.lastIndexOf("<"));
                    //check for the last page number
                    if(text.substring(end, text.lastIndexOf("<")).trim().length() > 0) {
                        start = text.indexOf("</book-part>");
                        System.out.println("Start:" + start);
                        if(start != -1) {
                            r.add(new FindResult(ed, start, true, "</book-part>" 
                                    , (new PagebreakTag(prevPage +1)).toString() + "\n</book-part>"));
                        }
                        prevPage++;
                        for(int i = 0; i< r.size(); i++)
                            System.out.println(r.get(i));
                    }
                }
                
                startPage = prevPage + 1;
                
                findResult.put(chapters.get(k), r);
            }
            
        } catch (BadLocationException ex) {
            Exceptions.printStackTrace(ex);
        } catch (IOException ex) {
            Exceptions.printStackTrace(ex);
        }
        return findResult;
    }

}
